﻿using AutoMapper;
using B.S.GridManage.Api.Read.Application.Command.Area;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.GridManage.Api.Read.Application.Handler.Area
{
    /// <summary>
    /// 获取区域树形数据的中介者处理类
    /// </summary>
    public class GetAreaTreeHandler : IRequestHandler<GetAreaTreeCommand, ApiResult<List<AreaTreeDto>>>
    {
        private readonly IBaseRepository<AreaModel> areaRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 注入资源
        /// </summary>
        /// <param name="areaRepo">区域仓储</param>
        /// <param name="mapper">automapper组件</param>
        public GetAreaTreeHandler(IBaseRepository<AreaModel> areaRepo,IMapper mapper)
        {
            this.areaRepo = areaRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<AreaTreeDto>>> Handle(GetAreaTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<AreaTreeDto>> res = new ApiResult<List<AreaTreeDto>>();//实例化响应包装类

            res.Code = ApiEnum.Success;//响应状态码 response status code
            res.Msg = "查询区域树数据成功!";//响应消息
            res.Data = GetAreaTreeByParentId(0L);//调用递归方法,通过父id获取所有下级区域

            return Task.FromResult(res) ;
                 
        }
        /// <summary>
        /// 通过父级id,递归形式查所有下级区域
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<AreaTreeDto> GetAreaTreeByParentId(long parentId)
        {
            //根据传过来的父级id查找所有子区域集合
            var areas = areaRepo.GetAll().Where(x => x.ParentId == parentId);
            var areaTreeDTOs = mapper.Map<List<AreaTreeDto>>(areas);//把查到的实体集合转成areadto集合
            foreach (var item in areaTreeDTOs) {
                item.Children = GetAreaTreeByParentId(item.Id);//把主键做作为子集的父id,查找所有子级区域
            }
            
            return areaTreeDTOs;
        }
    }
}
